const constraints = { audio: true };
let mediaRecorder;
let chunks = [];

navigator.mediaDevices.getUserMedia(constraints)
    .then(function (stream) {
        let audio = document.querySelector('audio');
        audio.srcObject = stream;
        mediaRecorder = new MediaRecorder(stream);

        let recordButton = document.getElementById('Record');

        recordButton.addEventListener('click', function () {
            if (recordButton.textContent == "录制音频") {
                mediaRecorder.start();
                recordButton.textContent = "完成录制"
            } else if (recordButton.textContent == "完成录制") {
                mediaRecorder.stop();
                recordButton.textContent = "录制音频"
            }
        });

        mediaRecorder.ondataavailable = function (e) {
            chunks.push(e.data);
        };

        mediaRecorder.onstop = function (e) {

            var audioBlob = new Blob(chunks, { 'type': 'audio/mp3' });
            var formData = new FormData();
            formData.append('audio', audioBlob, 'recording.mp3');

            fetch('http://101.43.241.226:8889/upload', {
                method: 'POST',
                body: formData
            })
                .then(response => {
                    if (response.ok) {
                        // 处理成功响应
                        return response.json(); // 解析响应内容为JSON格式
                    } else {
                        // 处理错误响应
                        throw new Error('请求失败');
                    }
                })
                .then(data => {
                    // 处理解析后的响应数据
                    console.log(data);
                    let label = document.getElementById('resultLabel');
                    label.innerHTML = data.name;
                })
                .catch(error => {
                    console.error('Error uploading recording:', error);
                });

            chunks = [];
        };
    })
    .catch(function (err) {
        console.log(err.name + ": " + err.message);
    });
